package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    //注入本地dao
    @Autowired
    private OrderSettingDao orderSettingDao;

    /*
        添加
     */
    @Override
    public void add(List<OrderSetting> list) {
        //遍历集合
        for (OrderSetting orderSetting : list) {
            //先通过调用dao层中根据日期查询方法,判断当前预约信息是否已经导入
            long result = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());

            //判断result是否大于0
            if (result > 0) {
                //则说明当前日期已经添加过预约人数了,只需要调用dao层中修改方法
                orderSettingDao.updateNumberByOrderDate(orderSetting);
            } else {
                //不大于0,说明此日期不存在,执行添加操作
                orderSettingDao.addOrderSetting(orderSetting);
            }
        }
    }

    /*
        根据月份获取预约信息
     */
    @Override
    public List<Map> getOrderSettingByMonth(String date) {

        //设置查询区间
        String beginDate = date + "-1";
        String endDate = date + "-31";

        //创建Map对象,用于封装查询区间
        Map map = new HashMap();
        map.put("beginDate", beginDate);
        map.put("endDate", endDate);

        //调用dao层
        List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByMonth(map);
        //创建响应对象集合
        List<Map> orderSettingData = new ArrayList<>();

        //遍历集合
        for (OrderSetting orderSetting : orderSettingList) {
            //创建Map对象,用于封装查询区间
            Map orderMap = new HashMap();
            //构建页面需要的数据格式
            orderMap.put("date", orderSetting.getOrderDate().getDate()); //获取日期
            orderMap.put("number", orderSetting.getNumber()); //获取可预约人数
            orderMap.put("reservations", orderSetting.getReservations()); //获取预约人数

            //添加集合中
            orderSettingData.add(orderMap);
        }

        return orderSettingData;
    }

    /*
        根据日期修改可预约人数
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if(count > 0){
            //当前日期已经进行了预约设置，需要进行修改操作
            orderSettingDao.updateNumberByOrderDate(orderSetting);
        }else{
            //当前日期没有进行预约设置，进行添加操作
            orderSettingDao.addOrderSetting(orderSetting); 
        }
    }
    //定时清理预约
    public void delete(String date) {
         orderSettingDao.dateDelete(date);
    }
}
